package com.xbxkj.api.app.mini.config.interceptor;

import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.xbxkj.api.app.mini.controller.MiniAppBaseController;
import com.xbxkj.api.app.mini.entity.MiniAppConst;
import com.xbxkj.commen.controller.BaseController;
import com.xbxkj.commen.controller.entity.ApiCode;
import com.xbxkj.commen.controller.helper.$;
import com.xbxkj.util.jwt.AuthSign;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by Zhang on 2018/8/26.
 */
@Configuration
@Slf4j
public class Localinterceptor extends MiniAppBaseController implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       String token= request.getHeader("Token");
       //获取redis中缓存的token键值的微信会话sessionKey
        if(StrUtil.hasBlank(token)||!AuthSign.verify(token)){
            renderJson(JSONObject.toJSONString($.error(ApiCode.login_time_out,"登陆失效")));
            return  false;
        }else{
            try {
                WxMaJscode2SessionResult cacheLoginJSON=JSONObject.parseObject(getJSONCache(token),WxMaJscode2SessionResult.class);
                request.setAttribute(MiniAppConst.sessionKey,cacheLoginJSON.getSessionKey());
                request.setAttribute(MiniAppConst.openId,cacheLoginJSON.getOpenid());
                request.setAttribute(MiniAppConst.unionid,cacheLoginJSON.getUnionid());
                request.setAttribute(MiniAppConst.userId,AuthSign.getUserIdByToken(token));
                return true;
            }catch (Exception e){
                renderJson(JSONObject.toJSONString($.error(ApiCode.login_time_out,"登陆失效")));
                return  false;
            }
        }
    }


    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}
